package com.lzj.jiangxindaojia.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.location.LocationManager;
import android.net.Uri;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.lzj.jiangxindaojia.R;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;


/**
 * Created by lizj on 2017/10/12.
 */

public class Utils {


    private static AlertDialog dialog;


    public static void showToast(Context context, String paramString) {
        dialog = new AlertDialog.Builder(context, R.style.AppBaseTheme1).create();
        dialog.show();
        Window localWindow = dialog.getWindow();
        localWindow.clearFlags(131072);
        localWindow.setContentView(R.layout.dialog_tips_one);
        localWindow.setGravity(17);
        localWindow.setLayout(-1, -2);
        LinearLayout localLinearLayout = (LinearLayout) localWindow.findViewById(R.id.ll_dialog);
        int j;
        int i;
        j = Color.parseColor("#FFFFFF");
        i = Color.parseColor("#FFFFFF");
        GradientDrawable localGradientDrawable = new GradientDrawable();
        localGradientDrawable.setColor(i);
        localGradientDrawable.setCornerRadius(10);
        localGradientDrawable.setStroke(5, j);
        localLinearLayout.setBackgroundDrawable(localGradientDrawable);
        TextView ok = ((TextView) localWindow.findViewById(R.id.tip_ok));
        TextView tip_title = ((TextView) localWindow.findViewById(R.id.tip_title));
        TextView tip_msg = ((TextView) localWindow.findViewById(R.id.tip_msg));
        tip_msg.setText(paramString);
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                dialog.dismiss();
            }
        });
    }

    public static void showToast(final Context context, String paramString, final Class<?> cls) {
        dialog = new AlertDialog.Builder(context, R.style.AppBaseTheme1).create();
        dialog.show();
        Window localWindow = dialog.getWindow();
        localWindow.clearFlags(131072);
        localWindow.setContentView(R.layout.dialog_tips_one);
        localWindow.setGravity(17);
        localWindow.setLayout(-1, -2);
        LinearLayout localLinearLayout = (LinearLayout) localWindow.findViewById(R.id.ll_dialog);
        int j;
        int i;
        j = Color.parseColor("#FFFFFF");
        i = Color.parseColor("#FFFFFF");
        GradientDrawable localGradientDrawable = new GradientDrawable();
        localGradientDrawable.setColor(i);
        localGradientDrawable.setCornerRadius(10);
        localGradientDrawable.setStroke(5, j);
        localLinearLayout.setBackgroundDrawable(localGradientDrawable);
        TextView ok = ((TextView) localWindow.findViewById(R.id.tip_ok));
        TextView tip_title = ((TextView) localWindow.findViewById(R.id.tip_title));
        TextView tip_msg = ((TextView) localWindow.findViewById(R.id.tip_msg));
        tip_msg.setText(paramString);
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View paramAnonymousView) {
                goNextActivity(context,cls);
                dialog.dismiss();
            }
        });
    }

    public static void setDrawableLeft(Context context, int drawableid, TextView textView) {
        Drawable drawable = context.getResources().getDrawable(drawableid);
        /// 这一步必须要做,否则不会显示.
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textView.setCompoundDrawables(drawable, null, null, null);
    }


    public static void goNextActivity(Context paramContext, Class<?> paramClass) {
        paramContext.startActivity(new Intent(paramContext, paramClass));
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        //获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }

        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {   //listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);  //计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight();  //统计所有子项的总高度
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        //listView.getDividerHeight()获取子项间分隔符占用的高度
        //params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }



    public static void closeOrshowKeyboard(Context context) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        //得到InputMethodManager的实例
        if (imm.isActive()) {
            //如果开启
            imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, InputMethodManager.HIDE_NOT_ALWAYS);
            //关闭软键盘，开启方法相同，这个方法是切换开启与关闭状态的
        }
    }

    public static boolean checkURL(String url) {
        boolean value = false;
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
            int code = conn.getResponseCode();
            System.out.println(">>>>>>>>>>>>>>>> " + code + " <<<<<<<<<<<<<<<<<<");
            if (code != 200) {
                value = false;
            } else {
                value = true;
            }
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return value;
    }

    public static Bitmap getBitmap(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }

    /**
     * 检测该包名所对应的应用是否存在
     *
     * @param packageName
     * @return
     */
    public static boolean checkPackage(String packageName, Context context) {
        if (packageName == null || "".equals(packageName))
            return false;
        try {
            ((Activity) context).getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 强制帮用户打开GPS
     * @param context
     */
    public static final void openGPS(Context context) {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(context, 0, GPSIntent, 0).send();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检测GPS是否打开
     *
     * @return
     */
    public static boolean checkGPSIsOpen(Context context) {
        boolean isOpen;
        LocationManager locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
        return isOpen;
    }


    /**
     * 判断 用户是否安装微信客户端
     */
    public static boolean isWeixinAvilible(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断 用户是否安装QQ客户端
     */
    public static boolean isQQClientAvailable(Context context) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                LogUtils.log("pn = "+pn);
                if (pn.equalsIgnoreCase("com.tencent.qqlite") || pn.equalsIgnoreCase("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }

}
